package com.baidu.health.service.impl;

import com.baidu.health.Vo.LoginInfoVo;
import com.baidu.health.Vo.UserInfoVo;
import com.baidu.health.Vo.UserVo;
import com.baidu.health.mapper.TbUserMapper;
import com.baidu.health.pojo.ResultResponse;
import com.baidu.health.pojo.TbUser;
import com.baidu.health.service.TbUserService;
import com.baidu.health.utils.IdWorker;
import com.baidu.health.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Override
    public ResultResponse selectloginusername(LoginInfoVo loginInfoVo) {
        String userName = loginInfoVo.getUsername();
        String userPassword = loginInfoVo.getPassword();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",userName);
        TbUser tbUser1 = tbUserMapper.selectOne(queryWrapper);
        if(tbUser1==null){
            return ResultResponse.FAILED(500,"用户名错误");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        boolean b = bCryptPasswordEncoder.matches(loginInfoVo.getPassword(), tbUser1.getUserPassword());
        if(!b){
            return ResultResponse.FAILED(500,"密码错误");
        }
        //String token = JwtUtils.createToken(tbUser1.getUserId().toString(), tbUser1.getUserName(), tbUser1.getUserRole().toString(), null);
        String token = (String) JwtUtils.createJWT(tbUser1.getUserId().toString(),tbUser1.getUserName(),tbUser1.getUserRole().toString());
        redisTemplate.opsForValue().set("token"+token,1,120, TimeUnit.MINUTES);
        Map<String,Object> data=new HashMap<>();
        data.put("accessToken",token);
        data.put("userId",tbUser1.getUserId());
        data.put("userName",tbUser1.getUserName());
        data.put("userRole",tbUser1.getUserRole());
        return ResultResponse.SUCCESS(data);
    }

    @Override
    public ResultResponse selectlogionuserphone(UserVo tbUser) {
        String phone1 = tbUser.getPhone();
        String code = tbUser.getPhoneCode();
        String phone = (String) redisTemplate.opsForValue().get(phone1);
        if(phone==null){
            return ResultResponse.FAILED(500,"手机号验证已失效");
        }
        if(!phone.equals(code)){
            return ResultResponse.FAILED(500,"验证码已经失效");
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_phone",phone1);
        TbUser tbUser1 = tbUserMapper.selectOne(queryWrapper);
        if(tbUser1==null) {
            return ResultResponse.FAILED(500, "不存在该手机号");
        }
        String token = (String) JwtUtils.createJWT(tbUser1.getUserId().toString(),tbUser1.getUserName(),tbUser1.getUserRole().toString());
        redisTemplate.opsForValue().set(token,1,120, TimeUnit.MINUTES);
        Map<String,Object> data=new HashMap<>();
        data.put("accessToken",token);
        data.put("userId",tbUser1.getUserId());
        data.put("userName",tbUser1.getUserName());
        data.put("userRole",tbUser1.getUserRole());
        return ResultResponse.SUCCESS(data);
    }
    @Override
    public ResultResponse getUserInfo(UserInfoVo userInfoVo) {
        String accessToken = userInfoVo.getAccessToken();
        Map<String,Object> data=new HashMap<>();
        ArrayList<String> permissions=new ArrayList<>();
        Claims claims = JwtUtils.parseJWT(accessToken);
        String id = claims.getId();
        String subject = claims.getSubject();
        System.out.println(id);
        System.out.println(subject);
        TbUser tbUser = tbUserMapper.selectById(id);
        permissions.add("admin");
        data.put("username",tbUser.getUserName());
        data.put("userid",tbUser.getUserId());
        data.put("userRole",tbUser.getUserRole());
        data.put("permissions",permissions);
        data.put("avatar",tbUser.getUserImage());
        return ResultResponse.SUCCESS(data);
    }
    @Override
    public ResultResponse loginOut() {
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse userSelect() {
        List<TbUser> tbUsers = tbUserMapper.selectList(null);
        return ResultResponse.SUCCESS(tbUsers);
    }

    @Override
    public ResultResponse userUpdate(Integer userId, Integer status) {
        TbUser tbUser=new TbUser();
        tbUser.setUserId(userId);
        if(status==1){
            IdWorker idWorker = new IdWorker();
            long l = idWorker.nextId();
            String str = Long.toString(l);
           tbUser.setUserName(str);
           tbUserMapper.updateById(tbUser);
        }else if(status ==2){
            tbUser.setUserImage("http://create-file.oss-cn-beijing.aliyuncs.com/test/c5775b6b-2af1-4472-8030-80d50fb80bf3.jpg");
            tbUserMapper.updateById(tbUser);
        }else{
            IdWorker idWorker = new IdWorker();
            long l = idWorker.nextId();
            String str = Long.toString(l);
            tbUser.setUserName(str);
            tbUser.setUserImage("http://create-file.oss-cn-beijing.aliyuncs.com/test/c5775b6b-2af1-4472-8030-80d50fb80bf3.jpg");
            tbUserMapper.updateById(tbUser);
        }
        return ResultResponse.SUCCESS("成功");
    }

    @Override
    public ResultResponse userUpdatepassword(UserVo userVo) {
        String username = userVo.getUsername();
        String password = userVo.getPassword();
        String checkPassword = userVo.getCheckPassword();
        if(!password.equals(checkPassword)){
            return ResultResponse.FAILED(500,"两次密码输入不一致");
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",username);
        TbUser tbUser = tbUserMapper.selectOne(queryWrapper);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        tbUser.setUserPassword(encode);
        tbUserMapper.updateById(tbUser);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse userMessage(Integer userid) {
        TbUser tbUser = tbUserMapper.selectById(userid);
        return ResultResponse.SUCCESS(tbUser);
    }

    @Override
    public ResultResponse authcode( String phone) {
        String redis = (String) redisTemplate.opsForValue().get(phone);
        if(redis!=null){
            return ResultResponse.FAILED(500,"验证码已存在");
        }
        amqpTemplate.convertAndSend("healthcare.exchanges","healthcare.queues",phone);
        return ResultResponse.SUCCESS("发送验证码成功");
    }

    @Override
    public ResultResponse register(UserVo userVo) {
        if(userVo.getUsername()=="" ||userVo.getPassword()=="" ||userVo.getPhone()=="" ||userVo.getPhoneCode()==""){
            return ResultResponse.FAILED(500,"请把信息给输入完成");
        }
        String username = userVo.getUsername();
        String password = userVo.getPassword();
        String phone = userVo.getPhone();
        String phoneCode = userVo.getPhoneCode();
        String phone1 = (String) redisTemplate.opsForValue().get(phone);
        if(phone1==null){
            return ResultResponse.FAILED(500,"手机号验证已失效");
        }
        if(!phone1.equals(phoneCode)){
            return ResultResponse.FAILED(500,"验证码已经失效");
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",username);
        TbUser tbUser1 = tbUserMapper.selectOne(queryWrapper);
        if(tbUser1!=null){
            return ResultResponse.FAILED(500,"用户名已被占用");
        }
        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("user_phone",phone);
        TbUser tbUser2 = tbUserMapper.selectOne(queryWrapper1);
        if(tbUser2!=null){
            return ResultResponse.FAILED(500,"手机号已被注册，一个手机号只能注册一个");
        }
        TbUser user=new TbUser();
        user.setUserName(username);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        user.setUserPassword(encode);
        user.setUserPhone(phone);
        user.setDeleted((byte) 1);
        user.setUserRole((long) 0);
        user.setCreateTime(new Date());
        user.setUserImage("http://create-file.oss-cn-beijing.aliyuncs.com/test/c5775b6b-2af1-4472-8030-80d50fb80bf3.jpg");
        tbUserMapper.insert(user);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse deleteduserId(Integer userId) {
        tbUserMapper.deleteById(userId);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse updateUser(TbUser tbUser) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",tbUser.getUserName());
        TbUser tbUser1 = tbUserMapper.selectOne(queryWrapper);
        if(tbUser1!=null){
            return ResultResponse.FAILED(500,"用户名已被占用");
        }
        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("user_email",tbUser.getUserEmail());
        TbUser tbUser2 = tbUserMapper.selectOne(queryWrapper1);
        if(tbUser2!=null){
            return ResultResponse.FAILED(500,"邮箱号已被占用");
        }
        tbUserMapper.updateById(tbUser);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse forgeTPassword(UserVo userVo) {
        String phone1 = userVo.getPhone();
        String phoneCode = userVo.getPhoneCode();
        String password = userVo.getPassword();
        String checkPassword = userVo.getCheckPassword();
        String phone = (String) redisTemplate.opsForValue().get(phone1);
        if(phone==null){
            return ResultResponse.FAILED(500,"验证码已失效请重新发送");
        }
        if(!phone.equals(phoneCode)){
            return ResultResponse.FAILED(500,"验证码错误，请重新输入");
        }
        if(!password.equals(checkPassword)){
            return ResultResponse.FAILED(500,"两次密码输入的不一致");
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_phone",phone1);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        TbUser tbUser = tbUserMapper.selectOne(queryWrapper);
        tbUser.setUserPassword(encode);
        tbUserMapper.updateById(tbUser);
        return ResultResponse.SUCCESS("密码重置成功");
    }

    @Override
    public ResultResponse updatePassword(TbUser tbUser) {
        tbUserMapper.updateById(tbUser);
        return ResultResponse.SUCCESS("重置密码成功");
    }
}